package com.kaiyidiannao.view;

import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.os.Handler;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.TextSwitcher;
import android.widget.ViewSwitcher;
import com.kaiyidiannao.activity.SecondHandHouse.SecondHandHouseDetail;
import com.kaiyidiannao.activity.auction.AuctionDetailActivity;
import com.kaiyidiannao.activity.daydaycoupon.DdcDetailActivity;
import com.kaiyidiannao.activity.foodpalace.FoodPalaceDetail;
import com.kaiyidiannao.activity.foodpalace.PlayDetailActivity;
import com.kaiyidiannao.activity.messageInfo.MessageInfoDetail;
import com.kaiyidiannao.activity.secondhandcar.SecondHandCarDetail;
import com.kaiyidiannao.activity.tour.TourLineDetailActivity;
import com.kaiyidiannao.data.DataCenter;
import com.kaiyidiannao.main.R;
import com.kaiyidiannao.model.bean.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


public class AutoTextView extends TextSwitcher implements  ViewSwitcher.ViewFactory , View.OnClickListener {

    private static final String TAG = "AutoTextView";

    private float mHeight;
    private Context mContext;
    //mInUp,mOutUp分别构成向下翻页的进出动画
    private Rotate3dAnimation mInUp;
    private Rotate3dAnimation mOutUp;

    //mInDown,mOutDown分别构成向下翻页的进出动画
    private Rotate3dAnimation mInDown;
    private Rotate3dAnimation mOutDown;

    private ArrayList<RollingDataBean> rollingDataBeans  = new ArrayList<RollingDataBean>(); //置顶滚动的数据
    private int selectedIdx = -1;

    private Handler handler = new Handler();
    private int i = 0;
    private Runnable runnable;


    public AutoTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.auto3d);
        mHeight = a.getDimension(R.styleable.auto3d_textSize, 16);
        a.recycle();
        mContext = context;
        init();

        DataCenter.rolling_current_module_id = DataCenter.moduleFlag.none;

        // 添加点击事件
        setOnClickListener(this);

        setVisibility(GONE);
    }

    private void init() {
        setFactory(this);
        mInUp = createAnim(-90, 0 , true, true);
        mOutUp = createAnim(0, 90, false, true);
        mInDown = createAnim(90, 0 , true , false);
        mOutDown = createAnim(0, -90, false, false);
        //TextSwitcher主要用于文件切换，比如 从文字A 切换到 文字 BuyStreetAdapter，
        //setInAnimation()后，A将执行inAnimation，
        //setOutAnimation()后，B将执行OutAnimation
        setInAnimation(mInUp);
        setOutAnimation(mOutUp);
    }

    /**
     * for out interface
     */
    public void startRolling() {

        if (rollingDataBeans.size() ==0) {
            setText("");
            return;
        }

        if (runnable == null) {
            runnable = new Runnable() {
                public void run () {
                    if (rollingDataBeans.size() != 0) {
                        i = i % rollingDataBeans.size();

                        AutoTextView.this.setText(rollingDataBeans.get(i).toString());
                        selectedIdx = i;

                        handler.postDelayed(this, 2000);
                        AutoTextView.this.next();
                        i++;
                    } else {
                        selectedIdx = -1;
                        AutoTextView.this.setText("");
                    }
                }
            };
            handler.removeCallbacks(runnable);
            handler.postDelayed(runnable,2000);
        } else {
            handler.removeCallbacks(runnable);
            handler.postDelayed(runnable,2000);
        }
    }

    private Rotate3dAnimation createAnim(float start, float end, boolean turnIn, boolean turnUp){
        final Rotate3dAnimation rotation = new Rotate3dAnimation(start, end, turnIn, turnUp);
        rotation.setDuration(800);
        rotation.setFillAfter(false);
        rotation.setInterpolator(new AccelerateInterpolator());
        return rotation;
    }

    //这里返回的TextView，就是我们看到的View
    @Override
    public View makeView() {
//        TextView t = new TextView(mContext);
//        t.setGravity(Gravity.CENTER);
//        t.setTextSize(mHeight);
//        t.setMaxLines(1);
//        t.setTextSize(DisplayUtil.dip2px(12, mContext));
//        t.setTextColor(Color.BLACK);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.auto_textview_layout, null);
//        return LayoutInflater.from(getContext()).inflate(R.layout.auto_textview_layout, null).setPadding(0,10,10,0);
        view.setPadding(0,15,10,0);
        return view;
    }
    //定义动作，向下滚动翻页
    public void previous(){
        if(getInAnimation() != mInDown){
            setInAnimation(mInDown);
        }
        if(getOutAnimation() != mOutDown){
            setOutAnimation(mOutDown);
        }
    }
    //定义动作，向上滚动翻页
    public void next(){
        if(getInAnimation() != mInUp){
            setInAnimation(mInUp);
        }
        if(getOutAnimation() != mOutUp){
            setOutAnimation(mOutUp);
        }
    }

    @Override
    public void onClick(View view) {
        Class classz = null;
        Intent intent = new Intent();
        int catid = 0;  // 跳转到详情的catid是固定的

        if (selectedIdx != -1 &&
                DataCenter.rolling_current_module_id != DataCenter.moduleFlag.none) {
            switch (DataCenter.rolling_current_module_id) {
                case daydaycoupon:
                    classz = DdcDetailActivity.class; //天天惠详情
                    catid = DataCenter.CATID_daydaycoupon;
                    break;
                case aution:
                    classz = AuctionDetailActivity.class; //拍拍乐详情
                    catid = DataCenter.CATID_acution;
                    break;
                case tour_line:
                    classz = TourLineDetailActivity.class; //旅游线路详情
                    catid = DataCenter.rolling_tour_module_id;
                    break;
                case messageInfo:
                    classz = MessageInfoDetail.class;
                    catid = DataCenter.CATID_MESSAGE_INF;
                    break;
                case foodpalace:
                    classz = FoodPalaceDetail.class; //美食城
                    catid = DataCenter.CATID_FOOD_PALACE;
                    break;
                case buystreet:
                    classz = FoodPalaceDetail.class; //十字街
                    catid = DataCenter.CATID_BUY_STREAT;
                    break;
                case play:
                    classz = PlayDetailActivity.class;
                    catid = DataCenter.CATID_PLAY;
                    break;
                case secondhandcar:
                    classz = SecondHandCarDetail.class;
                    catid = DataCenter.CATID_SECOND_CAR;
                    break;
                case SecondHandHouse:
                    classz = SecondHandHouseDetail.class;
                    catid = DataCenter.CATID_SECOND_HOUSE;
                    break;
            }

            if (classz != null){
                intent.setClass(DataCenter.context, classz);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra("itemid", rollingDataBeans.get(selectedIdx).getItemid());
                intent.putExtra("catid", catid); // 只用凑对去用
                DataCenter.context.startActivity(intent);
            }
        }

    }

    class Rotate3dAnimation extends Animation {
        private final float mFromDegrees;
        private final float mToDegrees;
        private float mCenterX;
        private float mCenterY;
        private final boolean mTurnIn;
        private final boolean mTurnUp;
        private Camera mCamera;

        public Rotate3dAnimation(float fromDegrees, float toDegrees, boolean turnIn, boolean turnUp) {
            mFromDegrees = fromDegrees;
            mToDegrees = toDegrees;
            mTurnIn = turnIn;
            mTurnUp = turnUp;
        }

        @Override
        public void initialize(int width, int height, int parentWidth, int parentHeight) {
            super.initialize(width, height, parentWidth, parentHeight);
            mCamera = new Camera();
            mCenterY = getHeight() / 2;
            mCenterX = getWidth() / 2;
        }

        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            final float fromDegrees = mFromDegrees;
            float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

            final float centerX = mCenterX ;
            final float centerY = mCenterY ;
            final Camera camera = mCamera;
            final int derection = mTurnUp ? 1: -1;

            final Matrix matrix = t.getMatrix();

            camera.save();
            if (mTurnIn) {
                camera.translate(0.0f, derection *mCenterY * (interpolatedTime - 1.0f), 0.0f);
            } else {
                camera.translate(0.0f, derection *mCenterY * (interpolatedTime), 0.0f);
            }
            camera.rotateX(degrees);
            camera.getMatrix(matrix);
            camera.restore();

            matrix.preTranslate(-centerX, -centerY);
            matrix.postTranslate(centerX, centerY);
        }
    }

    /**
     * 设置置顶滚动栏的数据(自动获取内容和itemid)
     * @param topBeanList
     * @param <k>
     */
    public <k extends Serializable> void setData3 (List<k> topBeanList) {


        rollingDataBeans.clear();
        selectedIdx = -1;

        setText("");
        if (topBeanList.size() == 0) {
            setVisibility(GONE);
            return;
        } else {
            setVisibility(VISIBLE);
        }

        int i = 0;
        for (Serializable bean : topBeanList) {
            String title = "";
            String hits = "";
            String itemid = "";

            if (bean instanceof DaydayCouponBean) {
                title =  ((DaydayCouponBean) bean).getTitle();
                hits = ((DaydayCouponBean) bean).getHits();
                itemid = ((DaydayCouponBean) bean).getItemid();

            } else if (bean instanceof PlayBean) {
                title =  ((PlayBean) bean).getTitle();
                hits = ((PlayBean) bean).getHits();
                itemid = ((PlayBean) bean).getItemid();

            } else if (bean instanceof TourBean) {
                title =  ((TourBean) bean).getTitle();
                hits = ((TourBean) bean).getHits();
                itemid = ((TourBean) bean).getItemid();

            } else if (bean instanceof SecondHandCar) {
                title =  ((SecondHandCar) bean).getTitle();
                hits = ((SecondHandCar) bean).getHits();
                itemid = ((SecondHandCar) bean).getItemid();

            }  else if (bean instanceof SecondHandHouse) {
                title =  ((SecondHandHouse) bean).getTitle();
                hits = ((SecondHandHouse) bean).getHits();
                itemid = ((SecondHandHouse) bean).getItemid();

            }  else if (bean instanceof Auction) {
                title =  ((Auction) bean).getTitle();
                hits = ((Auction) bean).getHits();
                itemid = ((Auction) bean).getItemid();

            }  else if (bean instanceof MessageBean) {
                title =  ((MessageBean) bean).getTitle();
                hits = ((MessageBean) bean).getHits();
                itemid = ((MessageBean) bean).getItemid();

            }

            // 处理字符串过长的问题
            int maxLength = 12;
            if(!TextUtils.isEmpty(title) && title.trim().length() > maxLength) {
                title = title.substring(0, maxLength) + "...";
            }

            // 处理hits为null
            hits = (TextUtils.isEmpty(hits) == true ? "0" : hits);

            rollingDataBeans.add(new RollingDataBean(title, hits, itemid));
            i++;
        }
    }
}